package com.yanyilu.basing.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yanyilu.basing.common.HttpRequest;
import com.yanyilu.basing.common.R;
import com.yanyilu.basing.entity.OpenidUser;
import com.yanyilu.basing.entity.User;
import com.yanyilu.basing.jwt.Audience;
import com.yanyilu.basing.mapper.OpenidUserMapper;
import com.yanyilu.basing.mapper.TotalTimeMileageMapper;
import com.yanyilu.basing.mapper.UserMapper;
import com.yanyilu.basing.service.IOpenidUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yanyilu.basing.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Sxx
 * @since 2020-10-26
 */
@Service
public class OpenidUserServiceImpl extends ServiceImpl<OpenidUserMapper, OpenidUser> implements IOpenidUserService {
    @Value("${appId}")
    private String appId;

    @Value("${appSecret}")
    private String appSecret;

    @Autowired
    Audience audience;

    @Autowired
    private OpenidUserMapper openidUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TotalTimeMileageMapper totalTimeMileageMapper;

    @Override
    @Transactional
    public R getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code";
        //发送请求
        String sr = HttpRequest.sendGet(url);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(sr);
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");
        String access_token = json.getString("access_token");
        //System.out.println(json);
        if(null == access_token){
            return R.error(501,"请重新进入");
        }

        OpenidUser openidUser  = openidUserMapper.selectById(openid);

        if(null == openidUser){

            //获取用户信息
            String url1 = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
            //发送请求
            String sr1 = HttpRequest.sendGet(url1);
            //解析相应内容（转换成json对象）
            JSONObject json1 = JSONObject.parseObject(sr1);
            String headimgurl = json1.getString("headimgurl");
            String username = json1.getString("nickname");
            System.out.println("username===="+username);
            //保存用户表
            User user = new User();
            user.setHeadImge(headimgurl);
            user.setUserName(username);
            user.setStatus(0);
            userMapper.insert(user);

            //保存openid userid关系表
            openidUser = new OpenidUser();
            openidUser.setUserId(user.getUserId());
            openidUserMapper.insert(openidUser.setOpenid(openid));
            String token = JwtTokenUtil.createJWT(user.getUserId().toString(), "username", "role", audience);
            return R.ok().put("user",user).put("token",token);

        }else{
            User user = openidUserMapper.getUserByOpenId(openid);
            String token = JwtTokenUtil.createJWT(user.getUserId().toString(), "username", "role", audience);
            return R.ok().put("user",user).put("token",token);
        }
    }
}
